<template>
  <el-form label-width="100">
    <el-form-item label="Sku名称">
      <el-input placeholder="Sku名称" v-model="skuParam.skuName" />
    </el-form-item>
    <el-form-item label="价格（元）">
      <el-input placeholder="价格（元）" v-model="skuParam.price" type="number" />
    </el-form-item>
    <el-form-item label="重量（克）">
      <el-input placeholder="重量（克)" v-model="skuParam.weight" />
    </el-form-item>
    <el-form-item label="Sku描述">
      <el-input placeholder="Sku描述" type="textarea" v-model="skuParam.skuDesc" />
    </el-form-item>
    <el-form-item label="平台属性">
      <el-form :inline="true">
        <el-form-item v-for="(item, _index) in attrArr" :label="item.attrName" :key="item.id">
          <el-select v-model="item.attrIdAndValueId" placeholder="请选择">
            <el-option v-for="(v, _i) in item.attrValueItemList" :key="v.id" :label="v.valueName"
              :value="`${item.id}:${v.id}`" />
          </el-select>
        </el-form-item>
      </el-form>
    </el-form-item>
    <el-form-item label="销售属性">
      <el-form :inline="true">
        <el-form-item v-for="(item, _index) in saleArr" :key="item.id" :label="item.saleAttrName">
          <el-select v-model="item.saleIdAndValueId" placeholder="请选择">
            <el-option v-for="(m, _i) in item.spuSaleAttrValueList" :label="m.saleAttrName"
              :value="`${item.id}:${m.id}`" />
          </el-select>
        </el-form-item>

      </el-form>
    </el-form-item>
    <el-form-item label="图片名称">
      <el-table :border="true" :data="imageArr" ref="tableRef">
        <el-table-column type="selection" width="80px" align="center"></el-table-column>
        <el-table-column label="图片" width="180">
          <!--插槽展示图片  -->
          <template #="{ row, $index }">
            <img :src="row.imageUrl" style="width: 100px; height: 100px;" />
          </template>
        </el-table-column>
        <el-table-column prop="imgName" label="名称" width="180" />
        <el-table-column label="操作">
          <!-- 插槽展示按钮 -->
          <template #="{ row, $index }">
            <el-button @click="handlerImageDefault(row)" type="primary" size="small">设置默认</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" size="default" @click="saveSku">保存</el-button>
      <el-button @click="cancel" type="primary" size="default">取消</el-button>
    </el-form-item>
  </el-form>

</template>

<script setup lang="ts">
import type { Response } from '@/api/type';
import type { SpuImageList, SpuImageVO, SpuSaleAttrList, SpuSaleAttrVO, SpuVO } from '@/api/product/spu/type';
// 获取商品属性
import { getAttrInfoList } from '@/api/product/attr';
import { ElMessage } from 'element-plus';
import { reqAddSku, reqSpuImageList, reqSpuSaleAttrList } from '@/api/product/spu';
import { reactive, ref } from 'vue';
import type { AttrValueList, AttrValueVO } from '@/api/product/attr/type';
import type { SkuAttrValueList, SkuParam, SkuSaleAttrValueList } from '@/api/product/sku/type';




// 平台属性
let attrArr = ref<AttrValueList>([]);
// 销售属性
let saleArr = ref<SpuSaleAttrList>([]);
// 图片的数据
let imageArr = ref<SpuImageList>([]);
// 收集table的实例信息
let tableRef = ref<any>();
// 收集sku参数信息
let skuParam = reactive<SkuParam>({
  category3Id: 0,
  spuId: 0,
  tmId: 0,
  skuName: '',
  price: 0,
  weight: 0,
  skuDesc: '',
  skuAttrValueList: [], // 平台属性
  skuSaleAttrValueList: [],
  skuDefaultImg: ''
});


// 保存sku
const saveSku = async () => {
  // 赋值平台属性
  skuParam.skuAttrValueList = attrArr
    .value
    .reduce((pre: SkuAttrValueList, next: AttrValueVO) => {
      if (next.attrIdAndValueId) {
        let [attrId, valueId] = next.attrIdAndValueId.split(':');
        pre.push({
          attrId,
          valueId
        })
      }
      return pre;
    }, []);
  // 赋值平台属性
  // attrArr.value.forEach((item) => {
  //   // 获取平台属性id和属性值id
  //   let [attrId, attrValueId] = item.attrIdAndValueId?.split(':') || [];
  //   // 添加到skuParam中
  //   skuParam.skuAttrValueList?.push({
  //     attrId: attrId,
  //     valueId: attrValueId
  //   })
  // })

  //  赋值销售属性
  skuParam.skuSaleAttrValueList = saleArr
    .value
    .reduce((pre: SkuSaleAttrValueList, next: SpuSaleAttrVO) => {
      if (next.saleIdAndValueId) {
        let [saleAttrId, saleAttrValueId] = next.saleIdAndValueId.split(':');
        pre.push({
          saleAttrId,
          saleAttrValueId
        });
      }
      return pre;
    }, []);
  // 赋值销售属性
  // saleArr.value.forEach((item) => {
  //   let [saleAttrId, saleAttrValueId] = item.saleIdAndValueId?.split(':') || [];
  //   skuParam.skuSaleAttrValueList?.push({
  //     saleAttrId: saleAttrId,
  //     saleAttrValueId: saleAttrValueId
  //   })
  // })
  //    添加sku
  let addSkuResult: Response<void> = await reqAddSku(skuParam);
  if (addSkuResult.code != 200) {
    ElMessage.error(addSkuResult.message);
    return;
  }
  //  通知父组件切换场景为0
  $emit('changeScene', { flag: 0, params: '' })
}
//  取消按钮
const cancel = () => {
  // 切换场景
  $emit('changeScene', { flag: 0, params: '' })
}

// 设置图片为默认的方法
const handlerImageDefault = (row: SpuImageVO) => {
  // 背景：清除所有选中
  imageArr.value.forEach((item) => {
    tableRef.value.toggleRowSelection(item, false);
  })
  // 复选框选中
  tableRef.value.toggleRowSelection(row, true);
  skuParam.skuDefaultImg = row.imgUrl as string;
}
// sku数据初始化
const initSkuData = async (category1Id: number, category2Id: number, spu: SpuVO) => {
  //  获取平台属性
  const category3Id = spu.category3Id as number;
  skuParam.category3Id = category3Id;
  skuParam.tmId = spu.tmId as number;
  let attrInfoListResult: Response<AttrValueList> = await getAttrInfoList(category1Id, category2Id, category3Id);
  if (attrInfoListResult.code != 200) {
    ElMessage.error(attrInfoListResult.message)
    return;
  }
  attrArr.value = attrInfoListResult.data || [];
  //获取销售属性
  let spuId = spu.id as number;
  skuParam.spuId = spuId;
  let spuSaleAttrListResult: Response<SpuSaleAttrList> = await reqSpuSaleAttrList(spuId);
  if (spuSaleAttrListResult.code != 200) {
    ElMessage.error(spuSaleAttrListResult.message);
    return;
  }
  saleArr.value = spuSaleAttrListResult.data || [];

  //  获取照片墙列表信息
  let spuImageListResult: Response<SpuImageList> = await reqSpuImageList(spuId);
  if (spuImageListResult.code != 200) {
    ElMessage.error(spuImageListResult.message);
    return;
  }
  imageArr.value = spuImageListResult.data || [];
}

// 当前子组件的对外暴露
defineExpose({
  initSkuData
})
// 自定义事件方法
let $emit = defineEmits(['changeScene']);
</script>

<style scoped lang="scss"></style>